var config = require('../../../config.json');
var uuid = require('uuid');
var logger = require('log4js').getLogger();
var request = require('request');
var sdp_server = config.sdp_server.host + ":" + config.sdp_server.port;
var messageAgent = require('../../../common/message.js');
var messageBroker = require('../../../messageBroker.js');

exports.addWorkspace = function(req, res, next){
    var task_id = uuid.v1();
    res.format_json({task_id: task_id}, 200);
    request.post(sdp_server + "/api/workspace/add", {form: req.body}, function (err, response, data) {
        var dataJson = JSON.parse(data);
        if(dataJson.code == 200){
            if(dataJson.data.task_id){
                messageAgent.getMessage(sdp_server + '/api/message/' + dataJson.data.task_id, function(msg){
                    if(msg.err){
                        logger.error(msg.err);
                        messageBroker.emit('create_workspace', {body: {msg: null}, err: msg.err});
                        messageBroker.emit(task_id, {task_id: task_id, body: {}, err: "工作空间创建失败"});
                    }else {
                        if(msg.isCompleted){
                            messageBroker.emit(task_id, {task_id: task_id, body: {msg: "工作空间创建完成"}, err: null});
                            messageBroker.emit('add_workspace', {body: {msg: "工作空间创建完成"}, err: null});
                        }
                        messageBroker.emit('create_workspace', {body: {msg: msg.msg}, err: null});
                    }

                })
            }
        }
    });

};


exports.deleteWorkspace = function (req, res, next) {
    var task_id = uuid.v1();
    res.format_json({task_id: task_id}, 200);
    request.post(sdp_server + "/api/workspace/delete", {form: req.body}, function (err, response, data) {
        var dataJson = JSON.parse(data);
        if(dataJson.code == 200){
            if(dataJson.data.task_id){
                messageAgent.getMessage(sdp_server + '/api/message/' + dataJson.data.task_id, function(msg){
                    if(msg.err){
                        logger.error(msg.err);
                        messageBroker.emit('delete_workspace', {body: {msg: null}, err: "删除工作空间失败"});
                        messageBroker.emit(task_id, {task_id: task_id, body: {}, err: "删除工作空间失败"});
                    }else {
                        if(msg.isCompleted){
                            messageBroker.emit(task_id, {task_id: task_id, body: {msg: "工作空间已删除"}, err: null});
                        }
                    }

                })
            }
        }
    });
};